package code.whmmm.util.yaml;

import org.yaml.snakeyaml.Yaml;
import code.whmmm.util.simple.StrUtil;
import code.whmmm.util.simple.ValueWrapper;

import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * <p style='color:red'><b>
 * 调用方法时，需要先调用 {@link YamlReader#readYaml(String)} !!!
 * </b></p>
 * <br/>
 * 创建时间: 2019/11/21 13:51
 *
 * @author Zero
 */
public class YamlReader {

    private static class SingletonHolder {
        private static final Map<String, Object> map = new HashMap<String, Object>();
    }

    /**
     * 加载 yml 配置信息
     *
     * @param path 路径，例如 /config.yml
     */
    public static void readYaml(String path) {
        loadYaml(path);
    }


    /**
     * @param path yml 路径，例如 /config.yml
     */
    private static void loadYaml(String path) {

        Map<String, Object> map = SingletonHolder.map;

        Yaml yaml = new Yaml();

        InputStream stream = YamlReader.class.getResourceAsStream(path);

        LinkedHashMap<String, Object> m = yaml.load(stream);

        createMap(map, "", m);

        isInit = true;

    }

    private static void createMap(Map<String, Object> map, String prefix, Object o) {

        if (o instanceof Map) {


            Map<String, Object> o1 = ((Map) o);

            Set<String> s = o1.keySet();
            for (String s1 : s) {
                String newPre = "";
                if (StrUtil.isBlank(prefix)) {
                    newPre = "" + s1;
                } else {
                    newPre = prefix + "." + s1;
                }
                Object o2 = o1.get(s1);
                createMap(map, newPre, o2);
            }
        } else {
            map.put(prefix, o);
        }
    }

    private static Boolean isInit = false;

    public static String get(String key) {
        if (!isInit) {
            loadYaml("/config.yml");
        }

        return ValueWrapper.getString(SingletonHolder.map.get(key));

    }

}